package com.store.app.imlife.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.google.gson.Gson;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.model.DBHelper_hy;
import com.hyphenate.easeui.model.HyUserDao;
import com.hyphenate.easeui.model.LeidaEventBean;
import com.hyphenate.easeui.model.UserEventBean;
import com.hyphenate.easeui.model.recordBean_hy;
import com.hyphenate.easeui.ui.EaseBaseActivity;
import com.store.app.LocationApplication;
import com.store.app.R;
import com.store.app.activity.AddContactsActivity;
import com.store.app.activity.AddMemberActivity;
import com.store.app.activity.LeidaActivity;
import com.store.app.bean.GroupDetailBean;
import com.store.app.bean.HXUserBean;
import com.store.app.bean.StoresDetailsBean;
import com.store.app.hyphenate.EaseChatFragment;
import com.store.app.hyphenate.runtimepermissions.PermissionsManager;
import com.store.app.imlife.adapter.UserAdapter;
import com.store.app.imlife.bean.HxCmdBean;
import com.store.app.imlife.bean.UserUrlBean;
import com.store.app.net.NetRequest;
import com.store.app.net.ifc.IOnHttpListener;
import com.store.app.utils.Utils;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;

/**


 */
public class ChatActivity extends EaseBaseActivity implements View.OnClickListener , IOnHttpListener {
    public static ChatActivity activityInstance;
    private EaseChatFragment chatFragment;
    private String toChatUsername,title_name;
    private String groupDesc;
    private TextView tv_title_name;
    private LinearLayout ll_return;
    private TextView tv_group_info;
    private TextView tv_group_menu;
    private PopupWindow popupWindow;
    private PopupWindow menuPopupWindow;
    private LinearLayout ll_parent;
    private GridView gridView;
    private UserAdapter adapter;
    private List<UserUrlBean> list = new ArrayList<UserUrlBean>();
    private NetRequest netRequest;
    private GroupDetailBean groupDetailBean;//群详情
    //数据库存储
    private DBHelper_hy db=null;
    private recordBean_hy rb=null;
    private String  my_im_id="";//我的环信id
    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        setContentView(R.layout.em_activity_chat);
        initView();
        initData();
        activityInstance = this;
        //get user id or group id
        if(db==null){
            db=new DBHelper_hy(this);
            rb=new recordBean_hy();
        }
        if(getIntent()!=null){
            toChatUsername = getIntent().getExtras().getString("userId");
            title_name= getIntent().getExtras().getString("groupName");
            groupDesc = getIntent().getExtras().getString("groupDesc");
            if(!TextUtils.isEmpty(title_name)){
                tv_title_name.setText(title_name);
                initPopwindow(title_name, groupDesc, "url");
            }
            int chatType = getIntent().getExtras().getInt(EaseConstant.EXTRA_CHAT_TYPE, EaseConstant.CHATTYPE_SINGLE);
            if(chatType== EaseConstant.CHATTYPE_GROUP) {
                tv_group_info.setVisibility(View.VISIBLE);
                tv_group_menu.setVisibility(View.VISIBLE);
//                initMenuData();
                if(TextUtils.isEmpty(title_name)) {
                    //查询群基本信息
                    netRequest.requestHXGroupDetails(2, toChatUsername);
                }
            }else if(chatType== EaseConstant.CHATTYPE_SINGLE){
                //单聊查询用户信息
                netRequest.requestHXIMUserDetail(3,toChatUsername);
                tv_group_info.setVisibility(View.GONE);
                tv_group_menu.setVisibility(View.GONE);
                //查询本地有没存用户头像
                String s_faceimg="";
                SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
                my_im_id = preferences.getString("im_user_id", "");
                if ( !TextUtils.isEmpty(my_im_id)) {
                    HyUserDao hyUserDao=rb.findMember_other(db,my_im_id);
                    if(hyUserDao!=null){
                        s_faceimg= hyUserDao.getFaceimg();
                        if (TextUtils.isEmpty(s_faceimg)&&!"null".equals(hyUserDao.getFaceimgid())){
                            netRequest.requestQueryStoresInfo(5);
                        }
                    }
                }
            }
        }
        int chatType = getIntent().getExtras().getInt(EaseConstant.EXTRA_CHAT_TYPE, EaseConstant.CHATTYPE_SINGLE);
        if(chatType==EaseConstant.CHATTYPE_GROUP) {
            initMenuData();
        }
        chatFragment = new EaseChatFragment();
        //pass parameters to chat fragment
        chatFragment.setArguments(getIntent().getExtras());
        getSupportFragmentManager().beginTransaction().add(R.id.container, chatFragment).commit();
//        initPopwindow("群标题", "群内容", "url");
        EventBus.getDefault().register(this);


    }


    private void initData(){
        netRequest =  new NetRequest(this);

    }

    /**
     * 模拟侧滑菜单用户数据
     */
    private void initMenuData() {
        netRequest.requestHXGroupMenberList(1,toChatUsername);
    }

    private void initPopwindow(String groupTitle, String content, String url) {
        View popupWindowView = getLayoutInflater().inflate(R.layout.pop_group_info, null);
        View closeView = popupWindowView.findViewById(R.id.rl_close);
        closeView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (popupWindow != null) {
                    popupWindow.dismiss();
                }
            }
        });
        TextView tvGroupTitle = (TextView) popupWindowView.findViewById(R.id.tv_group_title);
        tvGroupTitle.setText(groupTitle);
        TextView tvContent = (TextView) popupWindowView.findViewById(R.id.tv_content);
        tvContent.setText(content);
        popupWindow = new PopupWindow(popupWindowView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        //菜单背景色
//        ColorDrawable dw = new ColorDrawable(Color.parseColor("#cc000000"));
//        popupWindow.setBackgroundDrawable(dw);
        //宽度
        //popupWindow.setWidth(LayoutParams.WRAP_CONTENT);
        //高度
        //popupWindow.setHeight(LayoutParams.FILL_PARENT);
        //显示位置

//        popupWindow.showAtLocation(getLayoutInflater().inflate(R.layout.activity_chatandvideo, null), Gravity.RIGHT, 0, dip2px(ChatAndVideoActivity.this, 100));
//        //设置背景半透明
//        backgroundAlpha(0f);
        //关闭事件
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {

            }
        });
    }

    protected void initMenuPopupWindow() {
        View popupWindowView = getLayoutInflater().inflate(R.layout.pop_person, null);
        gridView = (GridView) popupWindowView.findViewById(R.id.gridview);
        gridView.setAdapter(adapter);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                menuPopupWindow.dismiss();
                if(position<list.size()) {
                UserUrlBean userUrlBean = list.get(position);
                //如果有聊天室则直接进入聊天室,没有则展开单聊
                if (!TextUtils.isEmpty(userUrlBean.getIm_user_id())) {
                    if(userUrlBean.getIm_user_id().equals(LocationApplication.im_user_id)){
                        return;
                    }
                    Intent intent = new Intent(ChatActivity.this, ChatActivity.class);
                    intent.putExtra("userId", userUrlBean.getIm_user_id());
                    intent.putExtra("groupName", userUrlBean.getNickname());
                    startActivity(intent);

                }
                }else{
                    if(position==list.size()){
                        Intent intent = new Intent(ChatActivity.this, AddContactsActivity.class);
                        intent.putExtra("type", 1);
                        intent.putExtra("groupid",toChatUsername);
                        startActivity(intent);
                    }else if(position==list.size()+1){
                        Intent intent = new Intent(ChatActivity.this, AddMemberActivity.class);
                        intent.putExtra("type", 2);
                        intent.putExtra("groupid",toChatUsername);
                        startActivity(intent);
                    }
                }
            }
        });
        menuPopupWindow = new PopupWindow(popupWindowView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.FILL_PARENT, true);
        menuPopupWindow.setAnimationStyle(R.style.AnimationRightFade);

        //菜单背景色
        ColorDrawable dw = new ColorDrawable(Color.parseColor("#cc000000"));
        menuPopupWindow.setBackgroundDrawable(dw);
        menuPopupWindow.showAtLocation(getLayoutInflater().inflate(R.layout.activity_chatandvideo, null), Gravity.RIGHT, 0, dip2px(ChatActivity.this, 100));
        //关闭事件
        menuPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {

            }
        });
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        activityInstance = null;
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        // make sure only one chat activity is opened
        String username = intent.getStringExtra("userId");
        if (toChatUsername.equals(username))
            super.onNewIntent(intent);
        else {
            finish();
            startActivity(intent);
        }
    }

    @Override
    public void onBackPressed() {
        chatFragment.onBackPressed();
       // if (EasyUtils.isSingleActivity(this)) {
           finish();
       // }
    }

    public String getToChatUsername() {
        return toChatUsername;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        PermissionsManager.getInstance().notifyPermissionsChange(permissions, grantResults);
    }

    private void initView() {
        tv_title_name=(TextView)findViewById(R.id.tv_title);
        ll_return = (LinearLayout) findViewById(R.id.ll_return);
        tv_group_info = (TextView) findViewById(R.id.tv_group_info);
        tv_group_menu = (TextView) findViewById(R.id.tv_group_menu);
        ll_return.setOnClickListener(this);
        tv_group_info.setOnClickListener(this);
        tv_group_menu.setOnClickListener(this);
        ll_parent = (LinearLayout) findViewById(R.id.ll_parent);
        adapter = new UserAdapter(list, this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_return:
                finish();
                break;
            case R.id.tv_group_info:
                if(popupWindow!=null){
                    popupWindow.showAtLocation(ll_parent, Gravity.CENTER, 0, 0);
                }
                break;
            case R.id.tv_group_menu:
                initMenuPopupWindow();
                break;
        }
    }

    /**
     * 接收透传消息
     *
     * @param bean 示例 true nba11 http://play.lss.qupai.me/kuangbao4257/kuangbao4257-1TIVH.flv?auth_key=1470899328-0-1878-32561518921e4b3c83223deda2f17e0f
     */
    public void onEvent(HxCmdBean bean) {
//        Log.v("zyl", "ChatActivity onEvent");
//        //开启直播还是关闭直播
//        String s_action = bean.action;
//        String[] d_action = s_action.split(" ");
//        String mDataSource = d_action[2];//直播地址
//        //开启直播
//        if (d_action[0].equals("true")) {
//            String user = d_action[1];
//            Log.i("mylog", user);
//            boolean isadd = false;
//            //查看列表内是否已经有此用户，如果有的话则跳过不处理
//            for (int i = 0; i < list.size(); i++) {
//                if (user.equals(list.get(i).getIm_user_id())) {
//                    list.get(i).setUrl(mDataSource);
//                    list.get(i).setIfLiveIn(true);
//                    runOnUiThread(new Runnable() {
//                        public void run() {
//                            adapter.setList(list);
//                            Log.v("zyl", "将用户" + "的状态设置为正在直播");
//                            adapter.notifyDataSetChanged();
//                        }
//                    });
//                    isadd = true;
//                    break;
//                }
//            }
//            Log.v("zyl", "开启直播时候是否已经有此用户：" + isadd);
//            if (isadd == false) {
//                UserUrlBean userUrlBean = new UserUrlBean(user, mDataSource, true);
//                list.add(userUrlBean);
//                runOnUiThread(new Runnable() {
//                    public void run() {
//                        adapter.notifyDataSetChanged();
//                    }
//                });
//            }
//        } else {
//            String user = d_action[1];
//            boolean isadd = false;
//            //查看列表内是否已经有此用户，如果有的话则跳过不处理
//            for (int i = 0; i < list.size(); i++) {
//                if (user.equals(list.get(i).getIm_user_id())) {
//                    list.get(i).setUrl("");
//                    list.get(i).setIfLiveIn(false);
//                    runOnUiThread(new Runnable() {
//                        public void run() {
//                            adapter.notifyDataSetChanged();
//                        }
//                    });
//                    isadd = true;
//                    break;
//                }
//            }
//            Log.v("zyl", "关闭直播时候是否已经有此用户：" + isadd);
//            if (isadd == false) {
//                mDataSource  = "";
//                UserUrlBean userUrlBean = new UserUrlBean(user, mDataSource, true);
//                list.add(userUrlBean);
//                runOnUiThread(new Runnable() {
//                    public void run() {
//                        adapter.setList(list);
//                        adapter.notifyDataSetChanged();
//                    }
//                });
//            }
//        }
    }
    HashMap<String,String> map_noimg=new HashMap<>();
    public void onEvent(UserEventBean bean) {
        int type = bean.type;
        if (type == 0) {
            if (map_noimg.get(bean.username) == null) {
                map_noimg.put(bean.username, bean.username);
                //单聊查询用户信息
                netRequest.requestHXIMUserDetail(4, bean.username);
            }
        }else if (type == 1) {
            initMenuData();
        }
    }
    //接收跳转到雷达界面
    public void onEvent(LeidaEventBean bean){
        if(1==bean.getType()){
           Intent intent=new Intent(ChatActivity.this, LeidaActivity.class);
            intent.putExtra("groupid",toChatUsername);
           startActivity(intent);
        }
    }
    @Override
    public void onAfinalFail() {

    }

    @Override
    public void onExecuteSuccess(int requestId, String result, String msg) {
        if(requestId==1){
            list.clear();

//            try {
//                JSONArray jsonArray=new JSONArray(result);
//                for(int i=0;i<jsonArray.length();i++){
//                    UserUrlBean bean=new UserUrlBean();
//                    JSONObject jsonObject = jsonArray.getJSONObject(i);
//                    bean.setIm_user_id(jsonObject.getString("im_user_id"));
//                    bean.setNickname(jsonObject.getString("nickname"));
//                    bean.setHead_pic_path(jsonObject.getString("head_pic_path"));
//
//                    list.add(bean);
//                }
//            } catch (JSONException e) {
//                e.printStackTrace();
//            }
            //通过群列表查询我的用户头像
            String s_faceimg="";
            SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
            String imuser = preferences.getString("im_user_id", "");
            if ( !TextUtils.isEmpty(imuser)) {
                HyUserDao hyUserDao=rb.findMember_other(db,imuser);
                if(hyUserDao!=null){
                    s_faceimg= hyUserDao.getFaceimg();
                }
            }
            try {
                Gson gson =  new Gson();
                JSONArray jsonArray=new JSONArray(result);
                for(int i=0;i<jsonArray.length();i++){
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    UserUrlBean userUrlBean = gson.fromJson(jsonObject.toString(),UserUrlBean.class);
                    if(TextUtils.isEmpty(s_faceimg)&&!TextUtils.isEmpty(imuser)){
                        if(imuser.equals(userUrlBean.getIm_user_id())&&!TextUtils.isEmpty(userUrlBean.getHead_pic_path())){
                            try {
                                String s_img=userUrlBean.getHead_pic_path();
                                rb.saveMember(db, "", imuser, ""
                                        , "",s_img , "0");
                                Log.i("mylog", "存入店东头像" + s_img);
                                new Thread(){
                                    public void run(){
                                        try {
                                            Thread.sleep(500);
                                            runOnUiThread(new Runnable() {
                                                public void run() {
                                                    chatFragment.setListViewRefresh();
                                                }

                                            });
                                        } catch (Exception e) {
                                        }
                                    }
                                }.start();
                            } catch (Exception e) {
                            }
                        }
                    }
                    list.add(userUrlBean);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            adapter.notifyDataSetChanged();
        }else if(requestId == 2){
            Gson gson = new Gson();
            groupDetailBean  = gson.fromJson(result, GroupDetailBean.class);
            title_name = groupDetailBean.getName();
            groupDesc = groupDetailBean.getDescription();
            tv_title_name.setText(title_name);
            initPopwindow(title_name, groupDesc, "url");
            if(!TextUtils.isEmpty(title_name)) {
                try {
                    rb.saveMember(db, "",toChatUsername, title_name
                            , "", "", "3");
                } catch (Exception e) {
                }
            }
        }else if(requestId == 3){
            Gson gson = new Gson();
            HXUserBean hxUserBean = gson.fromJson(result, HXUserBean.class);
            try {
                rb.saveMember(db, "", hxUserBean.getIm_user_id(), hxUserBean.getNickname()
                        , "", hxUserBean.getHead_pic_path(), "0");
            }catch (Exception e){
            }
            String nickname=hxUserBean.getNickname();
            if(!TextUtils.isEmpty(nickname)) {
                tv_title_name.setText(nickname);
            }
            new Thread(){
                public void run(){
                    try {
                        Thread.sleep(500);
                        runOnUiThread(new Runnable() {
                            public void run() {
                                chatFragment.setListViewRefresh();
                            }

                        });
                    } catch (Exception e) {
                    }
                }
            }.start();

        }else if(requestId == 4){
            Gson gson = new Gson();
            HXUserBean hxUserBean = gson.fromJson(result, HXUserBean.class);
            try {
                rb.saveMember(db, "", hxUserBean.getIm_user_id(), hxUserBean.getNickname()
                        , "", hxUserBean.getHead_pic_path(), "0");
            }catch (Exception e){
            }
            new Thread(){
                public void run(){
                    try {
                        Thread.sleep(500);
                        runOnUiThread(new Runnable() {
                            public void run() {
                                chatFragment.setListViewRefresh();
                            }

                        });
                    } catch (Exception e) {
                    }
                }
            }.start();
        }else if(requestId == 5) {

            JSONObject jsonObject = null;
            try {
                jsonObject = new JSONObject(result);
                Gson gson = new Gson();
                StoresDetailsBean storesDetailsBean = gson.fromJson(jsonObject.getJSONObject("detail").toString(), StoresDetailsBean.class);
                Map<String, String> map = Utils.getMapForJson(jsonObject.getJSONObject("doc_url").toString());
                String s_handpic=map.get(storesDetailsBean.getHead_pic_path());
                if(TextUtils.isEmpty(s_handpic)){
                    try {
                        rb.saveMember(db, "", my_im_id, ""
                                , "null","" , "0");
                        Log.i("mylog","存入店东头像null");
                    } catch (Exception e) {
                    }
                }else{
                    try {
                        rb.saveMember(db, "", my_im_id, ""
                                , "",s_handpic , "0");
                        Log.i("mylog", "存入店东头像" + s_handpic);
                        new Thread(){
                            public void run(){
                                try {
                                    Thread.sleep(500);
                                    runOnUiThread(new Runnable() {
                                        public void run() {
                                            chatFragment.setListViewRefresh();
                                        }

                                    });
                                } catch (Exception e) {
                                }
                            }
                        }.start();
                    } catch (Exception e) {
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }

    @Override
    public void onExecuteFail(int requestId, String msg) {
        Log.i("mylog", msg);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }
}
